package robot

import (
	"context"
	"encoding/base64"
	"encoding/json"
	"net/url"
	"sale-admin/config"
	"sale-admin/config/redis"
	"sale-admin/internal/app/grpc/client"
	"sale-admin/internal/app/grpc/protoc/devicec"
	"sale-admin/internal/app/web/schema"
	"sale-admin/internal/app/web/service"
	"sale-admin/internal/app/web/service/common"
	"sale-admin/internal/app/web/service/coupon"
	"sale-admin/internal/app/web/service/pay"
	"sale-admin/internal/dal"
	"sale-admin/internal/dao"
	"sale-admin/internal/define"
	"sale-admin/internal/models"
	"sale-admin/internal/pkg"
	"sale-admin/internal/pkg/points"
	"sort"
	"strconv"
	"strings"
	"time"

	"192.168.1.75/go-pkg/errorx"
	"192.168.1.75/go-pkg/helper"
	"192.168.1.75/go-pkg/logx"
	"github.com/go-pay/gopay/alipay"
	"github.com/go-pay/gopay/wechat"
	"github.com/shopspring/decimal"
	"gorm.io/gorm"
)

// 支付方式
type PayDataStruct struct {
	Type            string `json:"type" json_old:"Type"`
	Msg             string `json:"msg" json_old:"Msg"`
	Sort            int64  `json:"sort" json_old:"Sort"`
	BackgroundImage string `json:"background_image" json_old:"BackgroundImage"`
}

// 最终返回的数据结构
type OrderPaymentResult struct {
	OutTradeNo          string            `json:"out_trade_no" json_old:"OutTradeNo"`
	OrderName           string            `json:"order_name" json_old:"OrderName"`
	CreateResult        OrderCreateResult `json:"create_result" json_old:"CreateResult"`
	PayData             []PayDataStruct   `json:"pay_data" json_old:"PayData"`
	ChildOutTradeNoList []OutTradeNoList  `json:"child_out_trade_no_list" json_old:"ChildOutTradeNoList"`
}
type OutTradeNoList struct {
	OutTradeNo   string `json:"out_trade_no"`
	GoodsID      string `json:"goods_id"`
	ContainerNum string `json:"container_num"`
	Id           int64  `json:"id"`
}

// 支付信息结构
type OrderCreateResult struct {
	AliPayResult           alipay.TradePrecreateResponse `json:"ali_pay_result" json_old:"AliPayResult"`
	WechatPayResult        wechat.UnifiedOrderResponse   `json:"wechat_pay_result" json_old:"WechatPayResult"`
	StripeExPayResult      pkg.PayRsp                    `json:"stripe_ex_pay_result" json_old:"StripeExPayResult"`
	JuheWechatCreateResult string                        `json:"juhe_wechat_create_result" json_old:"JuheWechatCreateResult"`
	JuheAlipayCreateResult string                        `json:"juhe_alipay_create_result" json_old:"JuheAlipayCreateResult"`
}

func (r RobotService) CreateOrder(
	ctx context.Context, db *gorm.DB, remoteIP,
	salesID string,
	PaymentAmount float64, // 订单总金额。需要查询真实价格或者折扣价格，进行比较是否正确
	goodsData []schema.OrderGoodsDetail, // 创单的商品数据
	Type int,
	PaymentType int, // 【选填】安卓指定支付方式, 默认0
	OutTradeNo,
	OriginalOutTradeNo string,
	CouponCode string,
	orderSource int,
) (
	OrderPaymentResult OrderPaymentResult, // 返回给安卓的结果
	err error,
) {
	logx.Error(ctx, "CreateOrder", logx.Any("salesID", salesID))
	// 返回普通创建订单信息 和 加购商品
	// type 0 原始版本一般订单 	     不支持选择支付方式
	// type 7 赠送订单 				不支持选择支付方式
	// type 9 支持一次购买多件商品	 支持选择支付方式
	// 目前除赠送订单为7外，最新97版本的请求类型都为9
	if Type == 9 {
		// 也需要支持兑换码商品
		OrderPaymentResult, err = RobotService{}.CreateOrderPluralGoodsMore(ctx, db, remoteIP,
			salesID,
			PaymentAmount,
			goodsData,
			Type,
			PaymentType, // 【选填，指定支付方式 默认0】
			OutTradeNo,
			OriginalOutTradeNo, // 【选填，原始订单号】
			CouponCode,         // 【选填，优惠码号】
			orderSource,
			0,
		)
	} else {
		OrderPaymentResult, err = RobotService{}.CreateOrderPluralGoods(ctx, db, remoteIP,
			salesID,
			PaymentAmount,
			goodsData,
			Type,
			0, // 不指定支付方式
			OutTradeNo,
			OriginalOutTradeNo,
			"",
			orderSource,
			0,
		)
	}
	logx.Error(ctx, "CreateOrder", logx.Any("count before", len(OrderPaymentResult.PayData)))

	paymentShowType, err0 := RobotService{}.GetPaymentShowType(ctx, salesID)

	logx.Error(ctx, "CreateOrder", logx.Any("paymentShowType", paymentShowType))
	// Convert PayData to strongly typed slice for safer processing
	var typedPayData []PayDataStruct

	if err0 == nil {
		if paymentShowType == define.PaymentShowType_All {
			// typedPayData = OrderPaymentResult.PayData
			for _, pd := range OrderPaymentResult.PayData {
				logx.Error(ctx, "CreateOrder", logx.Any("PaymentShowType_Points pd.Type", pd.Type))
				// if pd.Type == "1" {
				// 	continue
				// }
				typedPayData = append(typedPayData, pd)
			}
		} else if paymentShowType == define.PaymentShowType_Points {
			for _, pd := range OrderPaymentResult.PayData {
				logx.Error(ctx, "CreateOrder", logx.Any("PaymentShowType_Points pd.Type", pd.Type))
				if pd.Type == "9" {
					typedPayData = append(typedPayData, pd)
				}
			}
		} else if paymentShowType == define.PaymentShowType_Common {
			for _, pd := range OrderPaymentResult.PayData {
				logx.Error(ctx, "CreateOrder", logx.Any("PaymentShowType_Common pd.Type", pd.Type))
				// if pd.Type == "1" {
				// 	continue
				// }
				if pd.Type != "9" {
					typedPayData = append(typedPayData, pd)
				}
			}
		}
	}
	OrderPaymentResult.PayData = typedPayData

	logx.Error(ctx, "CreateOrder", logx.Any("count after", len(OrderPaymentResult.PayData)))
	return
}

type mychildInfo struct {
	ChildOutTradeNo string  `json:"child_out_trade_no"`
	GoodsName       string  `json:"goods_name"`
	GoodsID         string  `json:"goods_id"`
	Price           float64 `json:"price"`
	DiscountPrice   float64 `json:"discount_price"`
	ChildCountData  string  `json:"child_count_data"`
}

// CreateOrderPluralGoodsMore 加购活动商品 之 机器创建订单
// !!! 积分商品、导流商品、赠送不需要选择支付方式
func (r RobotService) CreateOrderPluralGoodsMore(
	ctx context.Context,
	db *gorm.DB,
	remoteIP,
	salesID string,
	PaymentAmount float64, // 订单总金额。需要查询真实价格或者折扣价格，进行比较是否正确
	goodsData []schema.OrderGoodsDetail, // 创单的商品数据
	Type int,
	PaymentType int, // 【选填】安卓指定支付方式, 默认0
	OutTradeNo,
	OriginalOutTradeNo string,
	CouponCode string,
	orderSource int,
	expiredAt int64,
) (
	OrderPaymentResult OrderPaymentResult, // 返回给安卓的结果
	err error,
) {
	RobotInfo, robotExist := r.CheckRobotExist(ctx, db, salesID, "")
	if !robotExist {
		err = errorx.New("找不到机器人", -1)
		return
	}

	// 商户信息
	MerchantInfo, count, _ := dao.MerchantConfig{}.GetDetail(ctx, db, RobotInfo.ID)
	if count == 0 {
		err = errorx.New("商户信息不存在", -1)
		return
	}

	var OrderGoodsUseRC int
	TotalAmount := decimal.NewFromFloat(0)

	myChildSlice := make(map[int]mychildInfo)
	mychildOutList := []OutTradeNoList{}

	var oldDataString string // CountData 商品信息json
	var PointsGoods int      // 限制积分商品和普通商品不能同时购买
	var zeroGoods int        // 0元购商品。直接创建订单，和兑换码类似
	var OrderGoodsID string
	if len(goodsData) <= 0 {
		err = errorx.New("商品信息不能为空", -1)
		return
	}

	var RobotContainerMap = make(map[string]int)
	// 创单错误时，冻结库存扣减
	defer func() {
		if err != nil {
			var containers []string
			for container, num := range RobotContainerMap {
				db.Model(&models.MaRobotSalesInfo{}).
					Where("sales_id = ?", salesID).
					Where("container_num = ?", container).
					UpdateColumn("goods_reserve_inventory", gorm.Expr("goods_reserve_inventory - "+strconv.Itoa(num)))
				containers = append(containers, container)
			}
			logx.Error(ctx, "create order error",
				logx.Any("robot_name", RobotInfo.RobotName),
				logx.Any("container_num", strings.Join(containers, ",")),
				logx.Any("error", err.Error()))
			//推送创单失败告警消息
			alarmMsg := map[string]interface{}{
				"alarm_type": 1201,
				"robot_id":   RobotInfo.RobotName,
				"content":    "【货道】:" + strings.Join(containers, ",") + ",【错误】:" + err.Error(),
				"created_at": time.Now().Unix(),
			}
			jsonString, _ := json.Marshal(alarmMsg)
			rdb := redis.NewDB()
			rdb.LPush(ctx, define.RedisAlarmNotifyList, string(jsonString))
		}
	}()
	for k, v := range goodsData {
		robotContainers, _ := dao.RobotSalesInfo{}.List(ctx, dal.Q, RobotInfo.RobotName, v.GoodsID, 1, 1)
		if len(robotContainers) == 0 {
			err = errorx.New("机器商品没有设置或商品存货为空1", -1)
			return
		}
		if v.ContainerNum != "" { // 指定货道
			// 1. 检测货道信息
			var ContainerNumCount int64
			for _, rc := range robotContainers {
				if strconv.Itoa(rc.ContainerNum) == v.ContainerNum {
					ContainerNumCount++
				}
			}
			if ContainerNumCount == 0 {
				err = errorx.New("机器商品没有设置或商品存货为空2", -1)
				return
			}
		} else { // 未指定货道
			maxRestInventory := 0
			for _, robotV := range robotContainers {
				if (robotV.GoodsInventory - robotV.GoodsReserveInventory) >= maxRestInventory { // 选库存数量最多的货道
					maxRestInventory = robotV.GoodsInventory - robotV.GoodsReserveInventory
					v.ContainerNum = strconv.Itoa(robotV.ContainerNum)
				}
			}
		}

		{
			// 冻结库存+1
			UpdateRows := db.Model(&models.MaRobotSalesInfo{}).
				Where("sales_id = ?", RobotInfo.SalesID).
				Where("goods_id = ?", v.GoodsID).
				Where("container_num = ?", v.ContainerNum).
				Where("(goods_inventory - goods_reserve_inventory) > 0"). // 可用库存 > 0
				UpdateColumn("goods_reserve_inventory", gorm.Expr("goods_reserve_inventory + 1")).
				RowsAffected
			if UpdateRows <= 0 {
				err = errorx.New("机器商品没有设置或商品存货为空3", -1)
				return
			}
			RobotContainerMap[v.ContainerNum] += 1 // 机器货道 + 1
		}

		// 2. 检测商品信息
		GoodsInfo, err1 := dao.Goods{}.Detail(ctx, dal.Q, v.GoodsID)
		if err1 != nil || GoodsInfo.ID == "" {
			err = errorx.New("商品信息不存在", -1)
			return
		}
		// 【安卓价格】！=【数据库价格】时，检查商品是否有折扣。如果没有折扣，还不相同说明安卓的价格异常。
		if GoodsInfo.Price != v.Univalent {
			// 1. 该时间内商品是否有折扣 （关系链：关联商品（原价） 对应 优惠商品（折扣价））
			// 2. 折扣后的价格是否和安卓一致
			count := RobotGoods{}.CheckGoodsOfActivity(ctx, db, salesID)
			// 没有折扣 ---------- 目前为大部分商品都是没有设置折扣的
			if count == 0 {
				logx.Error(context.Background(), "price Exception", logx.Float64("goods_price", GoodsInfo.Price), logx.Float64("Univalent", v.Univalent))
				err = errorx.New("商品折扣不存在，商品价格异常", -1)
				// 写入订单错误提示。
				// 1. 机器识别码和名称 2.错误原因 3 请求的商品数据
				return
			}
			// 有折扣 ---- 后期会设置，判断商品价格与安卓给的是否相同
		}

		// 0元购商品 -- 不走第三方创单
		if GoodsInfo.GoodsType == 6 {
			// 走新的创单方法。也不需要走下面的金额校验等，和兑换码相同。
			zeroGoods = 1
		}

		if GoodsInfo.GoodsType == 4 {
			if PointsGoods != 0 && PointsGoods != 1 {
				err = errorx.New("积分商品与普通商品不能同时购买", -1)
				return
			}
			PointsGoods = 1 // 积分商品
		} else {
			if PointsGoods != 0 && PointsGoods != 2 {
				err = errorx.New("积分商品与普通商品不能同时购买", -1)
				return
			}
			PointsGoods = 2 // 普通商品
		}

		TotalAmount = TotalAmount.Add(decimal.NewFromFloat(v.Univalent))
		// 兑换码统计 --- 判断商品是否属于兑换码 ---
		if GoodsInfo.UseRC == 1 {
			OrderGoodsUseRC++ // 计算订单中使用兑换码的个数
		}

		if v.ChildOutTradeNo == "" {
			// 子订单号
			v.ChildOutTradeNo, _ = helper.UUID{}.String()
		} else {
			orderInfo, _ := dao.NewOrder(ctx, dal.Q).
				WithChildOutTradeNoCond(v.ChildOutTradeNo).
				OrderDetail()
			if orderInfo != nil {
				err = errorx.New("子订单号重复", -1)
				return
			}
		}

		// 生成childCountData
		childCountData := []schema.OrderGoodsDetail{}
		childCountData = append(childCountData, v)

		newDataByte, _ := json.Marshal(&childCountData)
		OldGoodsData := common.Order{}.CountDataNewToOld(string(newDataByte))
		oldDataByte, _ := json.Marshal(&OldGoodsData)
		oldDataString1 := strings.ReplaceAll(string(oldDataByte), `\\u`, `\u`)
		oldDataString = strings.ReplaceAll(string(oldDataByte), `\\u`, `\u`)

		// 返回子订单类别
		var mychildOne OutTradeNoList
		mychildOne.OutTradeNo = v.ChildOutTradeNo
		mychildOne.GoodsID = v.GoodsID
		mychildOne.ContainerNum = v.ContainerNum
		mychildOne.Id = v.ID
		// 追加
		mychildOutList = append(mychildOutList, mychildOne)
		// 差价
		myDiscountPrice := GoodsInfo.Price - v.Univalent
		myChildSlice[k] = mychildInfo{
			ChildOutTradeNo: v.ChildOutTradeNo,
			GoodsName:       v.GoodsName,
			GoodsID:         v.GoodsID,
			Price:           v.Univalent,
			DiscountPrice:   myDiscountPrice,
			ChildCountData:  oldDataString1,
		}
		OrderGoodsID = v.GoodsID
	}

	if OutTradeNo == "" {
		// 生成唯一订单号
		OutTradeNo, _ = helper.UUID{}.String()
	}

	// 判断优惠码使用场景
	couponCodeUseCase := 1
	if zeroGoods == 1 || len(goodsData) == OrderGoodsUseRC {
		couponCodeUseCase = 2
	}

	// 根据优惠码，获取优惠金额
	var couponDiscountAmount float64 // 折扣后的订单金额
	if CouponCode != "" {
		// 获取折扣金额
		_, _, _, _, couponDiscountAmount, err = coupon.CouponCode{}.Check(ctx, salesID, TotalAmount.InexactFloat64(), CouponCode, couponCodeUseCase, 0)
		if err != nil {
			return
		}
		// 核销锁定，消费一个子码
		err = coupon.CouponCode{}.ConsumeLock(ctx, CouponCode, OutTradeNo, time.Minute*5)
		if err != nil {
			return
		}
	}
	// 判断商品加起来的价格和需要支付的金额是否一致
	// 注：如果使用了优惠码，比较时需要把实付金额(PaymentAmount)加上优惠金额(DiscountAmount，用户少付的钱)一起比较
	if couponCodeUseCase == 1 && PaymentAmount != TotalAmount.InexactFloat64()-couponDiscountAmount {
		err = errorx.New("商品价格异常", -1)
		return
	}

	// 统一子单创建时间
	orderAddTime := time.Now()
	orderCreatedAt := orderAddTime.Unix()
	// 创建0元购商品订单(这个不需要支付方式、也不走第三方请求)
	if zeroGoods == 1 {
		// 写入订单表
		var InsertData models.MaOrder
		// 子订单号 -- 兑换码一次只能兑换一个
		InsertData.ChildOutTradeNo = myChildSlice[0].ChildOutTradeNo
		InsertData.MerchantID = RobotInfo.MerchantID
		InsertData.RobotName = RobotInfo.RobotName
		InsertData.Areas1 = RobotInfo.Areas1
		InsertData.Areas2 = RobotInfo.Areas2
		InsertData.Areas3 = RobotInfo.Areas3
		InsertData.Areas4 = RobotInfo.Areas4
		InsertData.Areas5 = RobotInfo.Areas5
		InsertData.SalesID = salesID
		InsertData.OutTradeNo = OutTradeNo
		InsertData.AddTime = orderAddTime
		InsertData.PaymentAmount = PaymentAmount
		InsertData.ActualAmount = PaymentAmount
		InsertData.CountData = oldDataString
		InsertData.PaymentID = 15
		InsertData.OrderStatus = 1
		InsertData.ModifyTime = orderAddTime
		InsertData.End = 0
		InsertData.CreatedDate = orderAddTime
		InsertData.CreatedAt = orderCreatedAt
		InsertData.GoodsID = goodsData[0].GoodsID
		InsertData.OrderSource = orderSource
		InsertData.ExpiredAt = expiredAt
		// 写入主订单表
		err = db.Model(&models.MaOrder{}).Create(&InsertData).Error
		if err != nil {
			err = errorx.New("订单创建失败", -1)
			return
		}
		// 写入订单详情
		var InsertDetailData models.MaOrderDetails
		InsertDetailData.ID = InsertData.OrderID
		InsertDetailData.UserName = MerchantInfo.Username
		InsertDetailData.SalesID = salesID
		InsertDetailData.AddTime = orderAddTime
		InsertDetailData.CreatedAt = orderCreatedAt
		InsertDetailData.AlipayCreatResult = "0元购商品"
		InsertDetailData.WechatCreatResult = "0元购商品"
		InsertDetailData.JuheWechatCreatResult = "0元购商品"
		InsertDetailData.JuheAlipayCreatResult = "0元购商品"
		InsertDetailData.PaymentAmount = PaymentAmount
		db.Model(&models.MaOrderDetails{}).Create(&InsertDetailData)
		PaymentTypeMap := service.RobotPayment{}.GetRobotPayments(context.Background(), db, salesID, PaymentType)
		// 只保留13Pos机器支付方式,其他不需要创单，不然会报错
		var filterPaymentTypes = make(map[string]int)
		for k, v := range PaymentTypeMap {
			if k == "13" {
				filterPaymentTypes[k] = v
			}
		}
		PaymentTypeMap = filterPaymentTypes

		// 开始生成支付二维码，返回给安卓
		OrderPaymentResult, err = RobotService{}.GetPaymentDetailToOrder(
			ctx,
			db,
			remoteIP,
			*MerchantInfo,
			OutTradeNo,
			salesID, OrderGoodsID,
			PaymentTypeMap,
			PaymentAmount,
		)
		// 0元购返回小程序链接
		var URL url.URL
		query := URL.Query()
		query.Add("sales_id", salesID)    // 机器码
		query.Add("order_id", OutTradeNo) // 订单号
		OrderPaymentResult.PayData = []PayDataStruct{
			{
				Type: "15", // 零元购
				Sort: 15,
				Msg:  config.Config.BaseUrl + "/mini-app-admin/qrcode/free-goods" + "?" + query.Encode(),
			},
		}
		OrderPaymentResult.ChildOutTradeNoList = mychildOutList
		OrderPaymentResult.OutTradeNo = OutTradeNo
		OrderPaymentResult.OrderName = "0元购商品"
		return
	}

	// 如果属于兑换商品，则创建兑换码订单。而且一次只能出一个
	// 全部使用兑换码的订单，否则都没有兑换码
	if len(goodsData) == OrderGoodsUseRC {
		// 写入订单表
		var InsertData models.MaOrder
		// 子订单号 -- 兑换码一次只能兑换一个
		InsertData.ChildOutTradeNo = myChildSlice[0].ChildOutTradeNo
		InsertData.PaymentID = 14
		InsertData.MerchantID = RobotInfo.MerchantID
		InsertData.RobotName = RobotInfo.RobotName
		InsertData.Areas1 = RobotInfo.Areas1
		InsertData.Areas2 = RobotInfo.Areas2
		InsertData.Areas3 = RobotInfo.Areas3
		InsertData.Areas4 = RobotInfo.Areas4
		InsertData.Areas5 = RobotInfo.Areas5
		InsertData.SalesID = salesID
		InsertData.OutTradeNo = OutTradeNo
		InsertData.AddTime = orderAddTime
		InsertData.CreatedDate = orderAddTime
		InsertData.PaymentAmount = PaymentAmount
		InsertData.ActualAmount = PaymentAmount
		InsertData.CountData = oldDataString
		InsertData.OrderStatus = 1
		InsertData.ModifyTime = orderAddTime
		InsertData.CreatedAt = orderCreatedAt
		InsertData.End = 0
		InsertData.GoodsID = goodsData[0].GoodsID
		InsertData.OrderSource = orderSource
		InsertData.ExpiredAt = expiredAt
		// 写入主订单表
		err = db.Model(&models.MaOrder{}).Create(&InsertData).Error
		if err != nil {
			err = errorx.New("订单创建失败", -1)
			return
		}
		// 写入订单详情
		var InsertDetailData models.MaOrderDetails
		InsertDetailData.ID = InsertData.OrderID
		InsertDetailData.UserName = MerchantInfo.Username
		InsertDetailData.SalesID = salesID
		InsertDetailData.AddTime = orderAddTime
		InsertDetailData.CreatedAt = orderCreatedAt
		InsertDetailData.AlipayCreatResult = "UseRC"
		InsertDetailData.WechatCreatResult = "UseRC"
		InsertDetailData.JuheAlipayCreatResult = "UseRC"
		InsertDetailData.JuheWechatCreatResult = "UseRC"
		InsertDetailData.PaymentAmount = PaymentAmount
		db.Model(&models.MaOrderDetails{}).Create(&InsertDetailData)

		OrderPaymentResult.ChildOutTradeNoList = mychildOutList
		OrderPaymentResult.OutTradeNo = OutTradeNo
		OrderPaymentResult.OrderName = "2023RC"
		return
	} else if OrderGoodsUseRC != 0 {
		err = errorx.New("订单内同时存在兑换码和非兑换码商品", -1)
		return
	}

	// ============================== 下面走的是普通的扫码支付创单流程了 ==================================
	if PointsGoods != 1 && PaymentAmount <= 0 {
		err = errorx.New("订单金额错误", -1)
		return
	}

	if PointsGoods == 1 && PaymentAmount < 0 {
		err = errorx.New("订单金额错误", -1)
		return
	}

	// 选择支付方式，获取商户的支付方式及支付配置  ------------  没有配置时，获取默认的支付方式
	PaymentTypeMap := service.RobotPayment{}.GetRobotPayments(context.Background(), db, salesID, PaymentType)
	// 1.积分商品仅保留积分支付
	// 2.金额为0时，清空支付方式map,防止微信支付宝0元创单问题
	if PointsGoods == 1 || PaymentAmount == 0 {
		if pointsID, ok := PaymentTypeMap["9"]; ok {
			// 【重新定义map】有积分支付时仅保留积分支付
			PaymentTypeMap = make(map[string]int)
			PaymentTypeMap["9"] = pointsID
		} else {
			PaymentTypeMap = make(map[string]int)
		}
	}
	// 普通商品，不返回永旺的积分支付
	if PointsGoods != 1 {
		if pointsID, ok := PaymentTypeMap["9"]; ok { // 有积分支付
			if pointsID == 2 { // 永旺积分
				delete(PaymentTypeMap, "9")
			}
		}
	}
	if len(PaymentTypeMap) == 0 {
		err = errorx.New("没有设置支付方式", -1)
		return
	}

	// 开始生成支付二维码，返回给安卓
	OrderPaymentResult, err = RobotService{}.GetPaymentDetailToOrder(
		ctx,
		db,
		remoteIP,
		*MerchantInfo,
		OutTradeNo,
		salesID, OrderGoodsID,
		PaymentTypeMap,
		PaymentAmount,
	)
	if err != nil {
		logx.Info(ctx, "获取支付信息错误", logx.Any("err", err))
		err = errorx.New("获取支付信息错误", -1)
		return
	}

	OrderPaymentResult.ChildOutTradeNoList = mychildOutList
	for _, v := range myChildSlice {
		// 写入订单表
		// 创建普通支付订单
		var InsertData models.MaOrder
		InsertData.MerchantID = MerchantInfo.ID
		InsertData.SalesID = salesID
		InsertData.OutTradeNo = OutTradeNo
		InsertData.ChildOutTradeNo = v.ChildOutTradeNo // 写入子订单信息
		InsertData.AddTime = orderAddTime
		InsertData.CreatedDate = orderAddTime
		InsertData.PaymentAmount = v.Price // 这个需要变成单个商品的金额
		InsertData.ActualAmount = v.Price
		InsertData.DiscountAmount = v.DiscountPrice
		InsertData.CountData = v.ChildCountData
		InsertData.ModifyTime = orderAddTime
		InsertData.CreatedAt = orderCreatedAt
		InsertData.End = 0
		InsertData.RobotName = RobotInfo.RobotName
		InsertData.PaymentID = int8(PaymentType)
		// 如果有优惠码，则写入优惠码号
		if CouponCode != "" {
			InsertData.CouponCode = CouponCode
			InsertData.DiscountAmount = couponDiscountAmount
		}
		InsertData.Areas1 = RobotInfo.Areas1
		InsertData.Areas2 = RobotInfo.Areas2
		InsertData.Areas3 = RobotInfo.Areas3
		InsertData.Areas4 = RobotInfo.Areas4
		InsertData.Areas5 = RobotInfo.Areas5
		InsertData.OrderStatus = 1                        // 创建成功
		InsertData.Remarks = "订单创建成功"                     // 备注
		InsertData.EndOutTradeNo = OutTradeNo             // 确认订单号
		InsertData.OrigialOutTradeNo = OriginalOutTradeNo // 原有购买订单号
		InsertData.GoodsID = v.GoodsID
		InsertData.OrderSource = orderSource
		InsertData.ExpiredAt = expiredAt
		err = db.Model(&models.MaOrder{}).Create(&InsertData).Error
		if err != nil {
			err = errorx.New("订单创建失败!", -1)
			return
		}

		// 写入订单详情
		var InsertDetailData models.MaOrderDetails
		AliPayRes, _ := json.Marshal(OrderPaymentResult.CreateResult.AliPayResult)
		WechatPayRes, _ := json.Marshal(OrderPaymentResult.CreateResult.WechatPayResult)
		StripeExPayRes, _ := json.Marshal(OrderPaymentResult.CreateResult.StripeExPayResult)

		InsertDetailData.ID = InsertData.OrderID
		InsertDetailData.UserName = MerchantInfo.Username
		InsertDetailData.SalesID = salesID
		InsertDetailData.AddTime = orderAddTime
		InsertDetailData.CreatedAt = orderCreatedAt
		InsertDetailData.AlipayCreatResult = string(AliPayRes)
		InsertDetailData.WechatCreatResult = string(WechatPayRes)
		InsertDetailData.StripeExCreateResult = string(StripeExPayRes)
		InsertDetailData.JuheAlipayCreatResult = OrderPaymentResult.CreateResult.JuheAlipayCreateResult
		InsertDetailData.JuheWechatCreatResult = OrderPaymentResult.CreateResult.JuheWechatCreateResult
		// 写入预选择的支付方式 ---- 执行订单【更新】存储用户选择的支付方式ID
		InsertDetailData.PaymentID = PaymentType
		db.Model(&models.MaOrderDetails{}).Create(&InsertDetailData)
	}
	return
}

// 创建订单
func (r RobotService) CreateOrderPluralGoods(ctx context.Context, db *gorm.DB, remoteIP, salesID string, PaymentAmount float64,
	goodsData []schema.OrderGoodsDetail, Type, PaymentType int,
	OutTradeNo, OriginalOutTradeNo, CouponCode string, orderSource int, expiredAt int64) (
	OrderPaymentResult OrderPaymentResult, err error,
) {
	RobotInfo, robotExist := r.CheckRobotExist(ctx, db, salesID, "")
	if !robotExist {
		err = errorx.New("找不到机器人", -1)
		return
	}

	// 商户信息
	MerchantInfo, count, _ := dao.MerchantConfig{}.GetDetail(ctx, db, RobotInfo.ID)
	if count == 0 {
		err = errorx.New("商户信息不存在", -1)
		return
	}

	var OrderGoodsUseRC int
	TotalAmount := decimal.NewFromFloat(0)
	var PointsGoods int // 限制积分商品和普通商品不能同时购买

	var OrderGoodsID string
	if len(goodsData) <= 0 {
		err = errorx.New("商品信息不存在", -1)
		return
	}
	for _, v := range goodsData {
		// 1. 检测货道信息
		var ContainerNumCount int64
		db.Model(&models.MaRobotSalesInfo{}).
			Where("sales_id = ?", RobotInfo.SalesID).
			Where("goods_id = ?", v.GoodsID).
			Where("container_num = ? and container_status = 1", v.ContainerNum).
			Count(&ContainerNumCount)
		if ContainerNumCount == 0 {
			err = errorx.New("机器商品没有设置或商品存货为空4", -1)
			return
		}
		// 2. 检测商品信息
		GoodsInfo, err1 := dao.Goods{}.Detail(ctx, dal.Q, v.GoodsID)
		if err1 != nil || GoodsInfo.ID == "" {
			err = errorx.New("商品信息不存在", -1)
			return
		}
		if GoodsInfo.Price != v.Univalent {
			err = errorx.New("商品价格异常", -1)
			return
		}
		// 兑换码统计
		if GoodsInfo.UseRC == 1 {
			OrderGoodsUseRC++
		}

		if GoodsInfo.GoodsType == 4 {
			if PointsGoods != 0 && PointsGoods != 1 {
				err = errorx.New("积分商品与普通商品不能同时购买", -1)
				return
			}
			PointsGoods = 1 // 积分商品
		} else {
			if PointsGoods != 0 && PointsGoods != 2 {
				err = errorx.New("积分商品与普通商品不能同时购买", -1)
				return
			}
			PointsGoods = 2 // 普通商品
		}
		TotalAmount = TotalAmount.Add(decimal.NewFromFloat(v.Univalent))
		OrderGoodsID = v.GoodsID
	}

	// 判断总价是否正确
	if TotalAmount.InexactFloat64() != PaymentAmount {
		err = errorx.New("商品价格异常", -1)
		return
	}
	if OutTradeNo == "" {
		// 生成唯一订单号
		OutTradeNo, _ = helper.UUID{}.String()
	}
	// 统一子单创建时间
	orderAddTime := time.Now()
	orderCreatedAt := orderAddTime.Unix()
	// 新的商品信息转老的商品信息存入订单
	newDataByte, _ := json.Marshal(&goodsData)
	OldGoodsData := common.Order{}.CountDataNewToOld(string(newDataByte))
	oldDataByte, _ := json.Marshal(&OldGoodsData)
	oldDataString := strings.ReplaceAll(string(oldDataByte), `\\u`, `\u`)
	// 全部使用兑换码的订单，否则都没有兑换码
	if len(goodsData) == OrderGoodsUseRC {
		// 写入订单表
		var InsertData models.MaOrder
		InsertData.MerchantID = RobotInfo.MerchantID
		InsertData.RobotName = RobotInfo.RobotName
		InsertData.Areas1 = RobotInfo.Areas1
		InsertData.Areas2 = RobotInfo.Areas2
		InsertData.Areas3 = RobotInfo.Areas3
		InsertData.Areas4 = RobotInfo.Areas4
		InsertData.Areas5 = RobotInfo.Areas5
		InsertData.SalesID = salesID
		InsertData.OutTradeNo = OutTradeNo
		InsertData.AddTime = orderAddTime
		InsertData.CreatedDate = orderAddTime
		InsertData.PaymentAmount = PaymentAmount
		InsertData.ActualAmount = PaymentAmount
		InsertData.CountData = oldDataString
		InsertData.OrderStatus = 1
		InsertData.ModifyTime = orderAddTime
		InsertData.CreatedAt = orderCreatedAt
		InsertData.End = 0
		InsertData.GoodsID = goodsData[0].GoodsID
		InsertData.OrderSource = orderSource
		err = db.Model(&models.MaOrder{}).Create(&InsertData).Error
		if err != nil {
			err = errorx.New("订单创建失败", -1)
			return
		}
		// 写入订单详情
		var InsertDetailData models.MaOrderDetails
		InsertDetailData.ID = InsertData.OrderID
		InsertDetailData.UserName = MerchantInfo.Username
		InsertDetailData.SalesID = salesID
		InsertDetailData.AddTime = orderAddTime
		InsertDetailData.CreatedAt = orderCreatedAt
		InsertDetailData.AlipayCreatResult = "UseRC"
		InsertDetailData.WechatCreatResult = "UseRC"
		InsertDetailData.JuheAlipayCreatResult = "UseRC"
		InsertDetailData.JuheWechatCreatResult = "UseRC"
		InsertDetailData.PaymentAmount = PaymentAmount
		db.Model(&models.MaOrderDetails{}).Create(&InsertDetailData)

		OrderPaymentResult.OutTradeNo = OutTradeNo
		OrderPaymentResult.OrderName = "2023RC"
		return
	} else if OrderGoodsUseRC != 0 {
		err = errorx.New("订单内同时存在兑换码和非兑换码商品", -1)
		return
	}

	if (PointsGoods != 1 && PaymentAmount <= 0) || (PointsGoods == 1 && PaymentAmount < 0) {
		err = errorx.New("订单金额错误", -1)
		return
	}
	// 赠送订单
	if Type == 7 && OriginalOutTradeNo != "" {
		// 写入订单表
		var InsertData models.MaOrder
		InsertData.MerchantID = RobotInfo.MerchantID
		InsertData.SalesID = salesID
		InsertData.OutTradeNo = OutTradeNo
		InsertData.AddTime = orderAddTime
		InsertData.CreatedDate = orderAddTime
		InsertData.PaymentAmount = PaymentAmount
		InsertData.ActualAmount = PaymentAmount
		InsertData.CountData = oldDataString
		InsertData.ModifyTime = orderAddTime
		InsertData.CreatedAt = orderCreatedAt
		InsertData.End = 0
		InsertData.RobotName = RobotInfo.RobotName
		InsertData.Areas1 = RobotInfo.Areas1
		InsertData.Areas2 = RobotInfo.Areas2
		InsertData.Areas3 = RobotInfo.Areas3
		InsertData.Areas4 = RobotInfo.Areas4
		InsertData.Areas5 = RobotInfo.Areas5
		InsertData.PaymentID = 7                          // 赠送订单
		InsertData.OrderStatus = 3                        // 默认未支付
		InsertData.Remarks = "赠送订单创建成功"                   // 备注
		InsertData.EndOutTradeNo = OutTradeNo             // 确认订单号
		InsertData.OrigialOutTradeNo = OriginalOutTradeNo // 原有购买订单号
		InsertData.GoodsID = goodsData[0].GoodsID
		InsertData.OrderSource = orderSource
		err = db.Model(&models.MaOrder{}).Create(&InsertData).Error
		if err != nil {
			err = errorx.New("订单创建失败", -1)
			return
		}
		// 写入订单详情
		var InsertDetailData models.MaOrderDetails
		InsertDetailData.ID = InsertData.OrderID
		InsertDetailData.UserName = MerchantInfo.Username
		InsertDetailData.SalesID = salesID
		InsertDetailData.AddTime = orderAddTime
		InsertDetailData.CreatedAt = orderCreatedAt
		InsertDetailData.AlipayCreatResult = "UseGive"
		InsertDetailData.WechatCreatResult = "UseGive"
		InsertDetailData.JuheAlipayCreatResult = OriginalOutTradeNo
		InsertDetailData.JuheWechatCreatResult = OriginalOutTradeNo
		InsertDetailData.PaymentAmount = PaymentAmount
		db.Model(&models.MaOrderDetails{}).Create(&InsertDetailData)

		OrderPaymentResult.OutTradeNo = OutTradeNo
		OrderPaymentResult.OrderName = "2023RC"
		return
	}

	// 选择支付方式，获取商户的支付方式及支付配置
	PaymentTypeMap := service.RobotPayment{}.GetRobotPayments(context.Background(), db, salesID, PaymentType)
	// 1.积分商品仅保留积分支付
	// 2.金额为0时，清空支付方式map,防止微信支付宝0元创单问题
	if PointsGoods == 1 || PaymentAmount == 0 {
		if pointsID, ok := PaymentTypeMap["9"]; ok {
			// 【重新定义map】有积分支付时仅保留积分支付
			PaymentTypeMap = make(map[string]int)
			PaymentTypeMap["9"] = pointsID
		} else {
			PaymentTypeMap = make(map[string]int)
		}
	}
	// 普通商品，不返回永旺的积分支付
	if PointsGoods != 1 {
		if pointsID, ok := PaymentTypeMap["9"]; ok { // 有积分支付
			if pointsID == 2 { // 永旺积分
				delete(PaymentTypeMap, "9")
			}
		}
	}
	if len(PaymentTypeMap) == 0 {
		err = errorx.New("没有设置支付方式", -1)
		return
	}
	// 大兴支付的需要前面加上S
	if _, ok := PaymentTypeMap["6"]; ok {
		OutTradeNo = "S" + OutTradeNo
	}

	OrderPaymentResult, err = RobotService{}.GetPaymentDetailToOrder(ctx, db, remoteIP, *MerchantInfo, OutTradeNo, salesID,
		OrderGoodsID, PaymentTypeMap, PaymentAmount)
	if err != nil {
		err = errorx.New("获取支付信息错误", -1)
		return
	}

	// 写入订单表
	// 创建普通支付订单 ***** 重要性，相当于占了95%的订单入口
	var InsertData models.MaOrder
	InsertData.MerchantID = MerchantInfo.ID
	InsertData.SalesID = salesID
	InsertData.OutTradeNo = OutTradeNo
	InsertData.AddTime = orderAddTime
	InsertData.CreatedDate = orderAddTime
	InsertData.PaymentAmount = PaymentAmount
	InsertData.ActualAmount = PaymentAmount
	InsertData.CountData = oldDataString
	InsertData.ModifyTime = orderAddTime
	InsertData.CreatedAt = orderCreatedAt
	InsertData.End = 0
	InsertData.RobotName = RobotInfo.RobotName
	InsertData.Areas1 = RobotInfo.Areas1
	InsertData.Areas2 = RobotInfo.Areas2
	InsertData.Areas3 = RobotInfo.Areas3
	InsertData.Areas4 = RobotInfo.Areas4
	InsertData.Areas5 = RobotInfo.Areas5
	InsertData.OrderStatus = 1                        // 创建成功
	InsertData.Remarks = "订单创建成功"                     // 备注
	InsertData.EndOutTradeNo = OutTradeNo             // 确认订单号
	InsertData.OrigialOutTradeNo = OriginalOutTradeNo // 原有购买订单号
	InsertData.GoodsID = goodsData[0].GoodsID
	InsertData.OrderSource = orderSource
	err = db.Model(&models.MaOrder{}).Create(&InsertData).Error
	if err != nil {
		err = errorx.New("订单创建失败", -1)
		return
	}

	AliPayRes, _ := json.Marshal(OrderPaymentResult.CreateResult.AliPayResult)
	WechatPayRes, _ := json.Marshal(OrderPaymentResult.CreateResult.WechatPayResult)
	StripeExPayRes, _ := json.Marshal(OrderPaymentResult.CreateResult.StripeExPayResult)
	// 写入订单详情表
	var InsertDetailData models.MaOrderDetails
	InsertDetailData.ID = InsertData.OrderID
	InsertDetailData.UserName = MerchantInfo.Username
	InsertDetailData.SalesID = salesID
	InsertDetailData.AddTime = orderAddTime
	InsertDetailData.CreatedAt = orderCreatedAt
	InsertDetailData.AlipayCreatResult = string(AliPayRes)
	InsertDetailData.WechatCreatResult = string(WechatPayRes)
	InsertDetailData.StripeExCreateResult = string(StripeExPayRes)
	InsertDetailData.JuheAlipayCreatResult = OrderPaymentResult.CreateResult.JuheAlipayCreateResult
	InsertDetailData.JuheWechatCreatResult = OrderPaymentResult.CreateResult.JuheWechatCreateResult
	InsertDetailData.PaymentAmount = PaymentAmount
	db.Model(&models.MaOrderDetails{}).Create(&InsertDetailData)
	return
}

// GetPaymentDetailToOrder 获取商户的支付方式和支付配置
// payment_type 1 微信 2 支付宝 3 聚合支付 4 支付宝人脸 5 支付宝扫码枪 6 大兴支付 8 stripe支付 9积分支付
func (r RobotService) GetPaymentDetailToOrder(
	ctx context.Context,
	db *gorm.DB,
	remoteIP string,
	MerchantInfo models.MaMerchantConfig,
	OutTradeNo,
	salesID, GoodsID string,
	PaymentTypeMap map[string]int,
	PaymentAmount float64,
) (
	res OrderPaymentResult,
	err error,
) {
	PayData := []PayDataStruct{}
	var WechatPayResult wechat.UnifiedOrderResponse
	var AliPayResult alipay.TradePrecreateResponse
	var StripeExWechatPayResult pkg.PayRsp
	var RobotInfo models.MaRobot
	db.Model(&models.MaRobot{}).
		Where("sales_id = ? and deleted = 0", salesID).
		Take(&RobotInfo)
	if RobotInfo.ID == "" {
		return
	}
	var PointsBackgroundImage string
	var PointsSort int64
	// 积分支付
	if _, ok := PaymentTypeMap["9"]; ok {
		// 初始化GRPC
		deviceClient, clientErr := client.GetDeviceAdminClient()
		if clientErr != nil {
			logx.Error(context.Background(), "grpc device client error", logx.Err(clientErr))
			return
		}

		// GRPC获取商场位置列表
		deviceReq := &devicec.LocationDetailReq{}
		deviceReq.LocationId = strconv.Itoa(RobotInfo.Areas3)
		deviceRes, err := deviceClient.LocationDetail(context.Background(), deviceReq)
		if deviceRes != nil && deviceRes.Code == 0 && err == nil {
			if deviceRes.Location.PointsId != "" {
				PointsSort = deviceRes.Location.PointsSort
				if PointsSort == 0 { //0不参与排序，默认顺序9
					PointsSort = 9
				}
				PointsBackgroundImage = deviceRes.Location.PointsBackgroundImage
			}
		}
	}
	logx.Info(ctx, "order payment type", logx.Any("OutTradeNo", OutTradeNo), logx.Any("PaymentTypeMap", PaymentTypeMap))
	for k, v := range PaymentTypeMap {
		if k == define.PaymentType_Wechat { // 1 微信
			WechatPayConfig, _ := dao.Payment{}.GetWechatPay(context.Background(), dal.Q, "", v)
			if len(WechatPayConfig) == 0 {
				err = errorx.New("微信没有配置具体的支付参数", -1)
				return
			}

			err = pay.WechatPay{}.ConfigInit(WechatPayConfig[0].WeChatAppID, WechatPayConfig[0].WeChatMchID,
				WechatPayConfig[0].WeChatAppKey, WechatPayConfig[0].CertFile)
			if err != nil {
				return
			}
			myPaymentAmount := decimal.NewFromFloat(PaymentAmount).Mul(decimal.NewFromInt(100)).IntPart()
			wxrsp, err1 := pay.WechatPay{}.NativePay(remoteIP, OutTradeNo, myPaymentAmount, WechatPayConfig[0].WeChatAppKey)
			if err1 != nil {
				logx.Error(context.Background(), "wechat pay error", logx.Any("error", err1.Error()))
				err = errorx.New("微信支付错误", -1)
				return
			}

			if wxrsp.ResultCode == "SUCCESS" {
				PayData = append(PayData, PayDataStruct{
					Type: "1",
					Sort: 1,
					Msg:  wxrsp.CodeUrl,
				})
			}
			WechatPayResult = wxrsp
		} else if k == define.PaymentType_Alipay { // 2 支付宝
			AliPayConfig, _ := dao.Payment{}.GetAliPay(context.Background(), dal.Q, "", v)
			if len(AliPayConfig) == 0 {
				err = errorx.New("支付宝没有配置具体的支付参数", -1)
				return
			}
			err1 := pay.Alipay{}.ConfigInit(AliPayConfig[0].AliPayAppID, AliPayConfig[0].AliPayPrivateKey)
			if err1 != nil {
				err = errorx.New("支付宝配置错误", -1)
				return
			}
			alrsp, err2 := pay.Alipay{}.DoPay(OutTradeNo, PaymentAmount)
			if err2 != nil {
				logx.Error(context.Background(), "alipay error", logx.Any("error", err2.Error()))
				err = errorx.New("支付宝支付错误", -1)
				return
			}
			if alrsp.Response.Code == "10000" {
				PayData = append(PayData, PayDataStruct{
					Type: "2",
					Sort: 2,
					Msg:  alrsp.Response.QrCode,
				})
			}
			AliPayResult = alrsp
		} else if k == define.PaymentType_AliMicro { // 4 支付宝人脸
			AliPayConfig, _ := dao.Payment{}.GetAliPay(context.Background(), dal.Q, "", v)
			if len(AliPayConfig) == 0 {
				err = errorx.New("支付宝没有配置具体的支付参数", -1)
				return
			}
			err1 := pay.Alipay{}.ConfigInit(AliPayConfig[0].AliPayAppID, AliPayConfig[0].AliPayPrivateKey)
			if err1 != nil {
				err = errorx.New("没有配置人脸支付的支付参数", -1)
				return
			}

			PayData = append(PayData, PayDataStruct{
				Type: "5",
				Sort: 5,
				Msg:  "1",
			})
		} else if k == define.PaymentType_AliScan { // 5 支付宝扫码枪
			AliPayConfig, _ := dao.Payment{}.GetAliPay(context.Background(), dal.Q, "", v)
			if len(AliPayConfig) == 0 {
				err = errorx.New("没有配置扫码支付的支付参数", -1)
				return
			}
			err1 := pay.Alipay{}.ConfigInit(AliPayConfig[0].AliPayAppID, AliPayConfig[0].AliPayPrivateKey)
			if err1 != nil {
				err = errorx.New("支付宝配置错误", -1)
				return
			}
			PayData = append(PayData, PayDataStruct{
				Type: "6",
				Sort: 6,
				Msg:  "1",
			})
		} else if k == "6" { // 6 大兴支付
			DaxingConfig, _ := dao.Payment{}.GetDaxingPay(context.Background(), dal.Q, "", v)
			if len(DaxingConfig) == 0 {
				err = errorx.New("没有配置支付参数", -1)
				return
			}

			pay.DaxingPay{}.DaxingInit(DaxingConfig[0].DxAppID, DaxingConfig[0].DxSellerID, DaxingConfig[0].DxMerchantID,
				DaxingConfig[0].DxShopID, DaxingConfig[0].DxShopID, DaxingConfig[0].DxAppKey)
			// 创建微信订单
			DaxingRsp2, DaxingErr2 := pay.DaxingPay{}.CreateOrder(ctx, "WX", OutTradeNo+"W", PaymentAmount*100, "")
			if DaxingErr2 != nil {
				err = errorx.New("大兴支付错误", -1)
				return
			}
			if DaxingRsp2.Header.ErrorCode == "0" && DaxingRsp2.Result.QRCode != "" {
				WxQRCode, _ := base64.StdEncoding.DecodeString(DaxingRsp2.Result.QRCode)
				PayData = append(PayData, PayDataStruct{
					Type: "4",
					Sort: 4,
					Msg:  string(WxQRCode),
				})
			}
			// 创建支付宝订单
			DaxingRsp1, DaxingErr1 := pay.DaxingPay{}.CreateOrder(ctx, "ALI_20", OutTradeNo+"A", PaymentAmount*100, "")
			if DaxingErr1 != nil {
				err = errorx.New("大兴支付错误", -1)
				return
			}
			if DaxingRsp1.Header.ErrorCode == "0" && DaxingRsp1.Result.QRCode != "" {
				AliQRCode, _ := base64.StdEncoding.DecodeString(DaxingRsp1.Result.QRCode)
				PayData = append(PayData, PayDataStruct{
					Type: "5",
					Sort: 5,
					Msg:  string(AliQRCode),
				})
			}
		} else if k == "8" { // 8 stripe支付
			StripeConfig, _ := dao.Payment{}.GetStripePay(context.Background(), dal.Q, "", v)
			if len(StripeConfig) == 0 {
				err = errorx.New("没有配置stripe支付的支付参数", -1)
				return
			}

			var URL url.URL
			query := URL.Query()
			query.Add("order_id", OutTradeNo)
			PayData = append(PayData, PayDataStruct{
				Type: "8",
				Sort: 8,
				Msg:  config.Config.BaseUrl + "/admin/pay/stripe-pay?" + query.Encode(),
			})
		} else if k == "9" { // 9 积分商城
			if v == 1 { // 正弘
				var URL url.URL
				query := URL.Query()
				query.Add("sales_id", salesID)          // 机器码
				query.Add("order_id", OutTradeNo+"P")   // 订单号+P
				query.Add("points_id", strconv.Itoa(v)) // 积分商城的id
				PayData = append(PayData, PayDataStruct{
					Type:            "9", //积分商城
					Sort:            PointsSort,
					Msg:             config.Config.BaseUrl + "/h5-page/points/index.html#/wechat?" + query.Encode(),
					BackgroundImage: PointsBackgroundImage,
				})
			} else if v == 2 { // 永旺
				var GoodsInfo models.MaGoodsInfo
				db.Model(&models.MaGoodsInfo{}).
					Where("goods_id = ? and deleted = 0", GoodsID).
					Take(&GoodsInfo)
				// 创单
				yongwangRes, yongwangErr := points.YongWangPoints{}.OrderCreate(ctx, OutTradeNo, GoodsInfo.GoodsName1, GoodsInfo.GoodsImage, 1, GoodsInfo.Points)
				if yongwangErr != nil {
					err = yongwangErr
					return
				}
				YongWangQueryURL := yongwangRes.PreUrl // todo
				PayData = append(PayData, PayDataStruct{
					Type:            "9", //积分商城
					Sort:            PointsSort,
					Msg:             YongWangQueryURL,
					BackgroundImage: PointsBackgroundImage,
				})
			} else if v == 3 || v == 4 {
				// 猫酷积分 || 赢商积分
				var URL url.URL
				query := URL.Query()
				query.Add("sales_id", salesID)          // 机器码
				query.Add("order_id", OutTradeNo+"P")   // 订单号+P
				query.Add("points_id", strconv.Itoa(v)) // 积分商城的id
				PayData = append(PayData, PayDataStruct{
					Type:            "9", //积分商城
					Sort:            PointsSort,
					Msg:             config.Config.BaseUrl + "/h5-page/points/index.html#/wechat?" + query.Encode(),
					BackgroundImage: PointsBackgroundImage,
				})
			} else if v == 5 { // 万象积分
				var URL url.URL
				query := URL.Query()
				query.Add("sales_id", salesID)          // 机器码
				query.Add("order_id", OutTradeNo+"P")   // 订单号+P
				query.Add("points_id", strconv.Itoa(v)) // 积分商城的id

				PayData = append(PayData, PayDataStruct{
					Type: "9", //积分商城
					Sort: PointsSort,
					Msg:  config.Config.BaseUrl + "/mini-app-admin/qrcode/points-goods" + "?" + query.Encode(),
				})
			}
		} else if k == "10" { // 10 stripe_ex支付
			myPaymentAmount := decimal.NewFromFloat(PaymentAmount).Mul(decimal.NewFromInt(100)).IntPart()
			if myPaymentAmount < 50 {
				err = errorx.New("stripe支付错误", -1)
				return
			}
			stripeRes, err1 := pkg.StripeEx{}.Pay(ctx, myPaymentAmount)
			if err1 != nil || stripeRes.CheckoutURL == "" {
				err = errorx.New("stripe支付错误", -1)
				return
			}
			PayData = append(PayData, PayDataStruct{
				Type: "10",
				Sort: 10,
				Msg:  stripeRes.CheckoutURL,
			})
			StripeExWechatPayResult = stripeRes

		} else if k == "12" { // 12 小天才支付，格式和微信的一样
			WechatPayConfig, _ := dao.Payment{}.GetXiaotiancaiPay(context.Background(), dal.Q, "", v)
			if len(WechatPayConfig) == 0 {
				err = errorx.New("小天才没有配置具体的支付参数", -1)
				return
			}
			// 获取所需信息并验证
			err = pay.WechatPay{}.ConfigInit(WechatPayConfig[0].WeChatAppID, WechatPayConfig[0].WeChatMchID,
				WechatPayConfig[0].WeChatAppKey, WechatPayConfig[0].CertFile)
			if err != nil {
				return
			}
			myPaymentAmount := decimal.NewFromFloat(PaymentAmount).Mul(decimal.NewFromInt(100)).IntPart()
			wxrsp, err1 := pay.WechatPay{}.NativePay(remoteIP, OutTradeNo, myPaymentAmount, WechatPayConfig[0].WeChatAppKey)
			if err1 != nil {
				logx.Error(context.Background(), "wechat pay error", logx.Any("error", err1.Error()))
				err = errorx.New("小天才支付错误", -1)
				return
			}

			if wxrsp.ResultCode == "SUCCESS" {
				PayData = append(PayData, PayDataStruct{
					Type: "12",
					Sort: 12,
					Msg:  wxrsp.CodeUrl,
				})
			}
		} else if k == "13" {
			// POS机支付
			PosPayConfig, _ := dao.Payment{}.GetPOSPay(context.Background(), dal.Q, "", v)
			if len(PosPayConfig) == 0 {
				err = errorx.New("POS支付没有配置具体的支付参数", -1)
				return
			}
			PayData = append(PayData, PayDataStruct{
				Type: "13",
				Sort: 13,
				Msg:  "POS机支付",
			})
		} else if k == "16" {
			var URL url.URL
			query := URL.Query()
			query.Add("sales_id", salesID)    // 机器码
			query.Add("order_id", OutTradeNo) // 订单号

			PayData = append(PayData, PayDataStruct{
				Type: "16", // 小程序
				Sort: 16,
				Msg:  config.Config.BaseUrl + "/mini-app-admin/qrcode/goods" + "?" + query.Encode(),
			})
		}
	}
	sort.Slice(PayData, func(i, j int) bool {
		return PayData[i].Sort < PayData[j].Sort
	})
	Result := OrderPaymentResult{}
	Result.PayData = PayData
	Result.OutTradeNo = OutTradeNo
	Result.OrderName = strconv.Itoa(time.Now().Year())
	Result.CreateResult = OrderCreateResult{
		AliPayResult:           AliPayResult,
		WechatPayResult:        WechatPayResult,
		StripeExPayResult:      StripeExWechatPayResult,
		JuheWechatCreateResult: "",
		JuheAlipayCreateResult: "",
	}
	return Result, nil
}
